using UnityEngine;
using System.Collections;

public class menu_sel_char : MonoBehaviour {

	public GUIText texto;
	Transform PegaObj;	
	GameObject PegGBObjs;
	string PrefabName;
	string idCharacter;
	bool EhMaster = false;
	
	public string IP = "127.0.0.1";
	public int Port = 25001;
	
	void Start () {
		StartCoroutine(loginMaster_());
	}
	
	void Update () {		
 		
		if (Input.GetMouseButtonUp(0)) {
			RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit)){	
				PegaObj =  hit.transform;
				PegGBObjs = hit.transform.gameObject;
				if(PegaObj.tag == "CharPerso"){
					PrefabName = PegaObj.name;
					int pos = PrefabName.IndexOf("(Clone)");					
					idCharacter = PrefabName.Substring(0,pos); 
					hit.transform.renderer.material.color = Color.green;
				}
			}
        }
		
	}
	
	void OnGUI() {
		if (GUI.Button (new Rect(500, 320,100,30),"Criar")){
			StartCoroutine(new_char_());					
		}
		if (GUI.Button (new Rect(500, 357,100,30),"Excluir")){
			StartCoroutine(delete_char_());					
		}
		if (GUI.Button (new Rect(500, 394,100,30),"Voltar")){
			Application.LoadLevel(0);					
		}
		if (EhMaster){
			if (GUI.Button (new Rect(100, 320,100,30),"Tela Master")){
				Application.LoadLevel(1);					
			}	
		}
		if(Network.peerType == NetworkPeerType.Disconnected){
			if (GUI.Button (new Rect(258, 400,100,30),"Entrar")){				
				Network.Connect(IP,Port);
				Application.LoadLevel(4);					
			}
		}
		
	}
	
	IEnumerator new_char_(){
		
		WWWForm form = new WWWForm();
		
		form.AddField("idLogin", constant_sistem.idUsuari_Atual);
						
		WWW webRequest = new WWW(constant_sistem.db_url + "character_cont.php", form);
		
		yield return webRequest;
		
		if (webRequest.error !=null) {
			Debug.Log(webRequest.error);
		} else { 
			Debug.Log(webRequest.text); 
			if(webRequest.text != "5") {
				Application.LoadLevel(3);				
			} else {
//				texto.text = "Voce nao pode criar mais personagens!";
			}
		}
	}
	
	IEnumerator delete_char_(){
				
		WWWForm form = new WWWForm();
		
		form.AddField("idLogin", idCharacter);
						
		WWW webRequest = new WWW(constant_sistem.db_url + "character_excluir.php", form);
		
		yield return webRequest;
		
		if (webRequest.error !=null) {
			Debug.Log(webRequest.error);
		} else { 
			if(webRequest.text != "0") {
				Destroy(GameObject.Find(PrefabName));
			} else {
//				texto.text = "Voce nao pode excluir esse personagens!";
			}
		}
	}
	
	IEnumerator loginMaster_(){
				
		WWWForm form = new WWWForm();
		
		form.AddField("idLogin", constant_sistem.idUsuari_Atual);
						
		WWW webRequest = new WWW(constant_sistem.db_url + "login_master.php", form);
		
		yield return webRequest;
		
		if (webRequest.error !=null) {
		} else {
				if (webRequest.text == "100"){
					EhMaster = true;
				}
			} 		
	}
}
